﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection.Metadata;
using XL.Crawler.Core;
using XL.Crawler.Core.Crawlers;
using XL.Crawler.Core.Crawlers.CrawlerEventArgs;

namespace XL.Crawler.Api
{
    /// <summary>
    /// 后台任务
    /// </summary>
    internal class CrawlerTaskBackgroundService : BackgroundService, IHostedService
    {

        /// <summary>
        /// 容器提供者
        /// </summary>

        private readonly IServiceScopeFactory _serviceScopeFactory;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CrawlerTaskBackgroundService> _logger;


        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="serviceScopeFactory"></param>
        public CrawlerTaskBackgroundService(IServiceScopeFactory serviceScopeFactory, ILogger<CrawlerTaskBackgroundService> logger)
        {
            _serviceScopeFactory = serviceScopeFactory;
            _logger = logger;
        }
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await StartCrawler();
            }
        }
        /// <summary>
        /// 开始执行爬虫
        /// </summary>
        private async Task StartCrawler()
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                IEnumerable<ICrawler>? crawlers = scope.ServiceProvider.GetServices<ICrawler>();

                if (crawlers != null && crawlers.Any())
                {
                    foreach (ICrawler crawler in crawlers)
                    {
                        ShowLog(crawler);
                        await crawler.StartAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 显示日志
        /// </summary>
        /// <param name="crawler"></param>
        private void ShowLog([NotNull] ICrawler crawler)
        {
            crawler.OnStartEvent += (object o, StartEventArgs e) =>
            {
                _logger.LogInformation($"[{e.DateTime.ToString("HH:ss:FFFF")}][{o.GetType().Name}]开始");
            };
            crawler.OnExceptionEvent += (object o, ExceptionEventArgs e) =>
            {
                _logger.LogInformation($"[{e.DateTime.ToString("HH:ss:FFFF")}][{o.GetType().Name}]异常,{e.Exception}");

            };
            crawler.OnCompletedEvent += (object o, CompletedEventArgs e) =>
            {
                _logger.LogInformation($"[{e.DateTime.ToString("HH:ss:FFFF")}][{o.GetType().Name}]完成,{e.Data}");
            };
        }
    }
}
